package de.pharmacontrol.psa.beans;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import de.pharmacontrol.pilot.entities.User;
import de.pharmacontrol.psa.beans.interfaces.UserService;

@Stateless
public class UserServiceBean implements UserService {

	@PersistenceContext(unitName = "pilot")
	protected EntityManager em;

	@Override
	public User createUser(String name, String description) {
		User user = new User();
		user.setName(name);
		user.setDescription(description);
		em.persist(user);
		return user;
	}

	@Override
	public User findUserByName(String name) {
		try {
			return em.createQuery("select u from User u where u.name = :name", User.class).setParameter("name", name).getSingleResult();
		} catch (NoResultException nre) {
			return null;
		}
	}

	@Override
	public List<User> findUserByPattern(String pattern) {
		if (pattern == null || pattern.trim().isEmpty()){
			return findAllUser();
		}
		try {
			return em.createQuery("select u from User u where u.name like :name", User.class).setParameter("name",  "%" + pattern + "%").getResultList();
		} catch (NoResultException nre) {
			return null;
		}
	}
	
	@Override
	public User updateUser(User user) {
		return em.merge(user);
	}

	@Override
	public List<User> findAllUser() {
		try {
			return em.createQuery("select u from User u", User.class).getResultList();
		} catch (NoResultException nre) {
			return null;
		}
	}

	@Override
	public boolean validateUser(String name, String password) {
		try {
			return em.createQuery("select u from User u where u.name = :name and u.password = :pwd", User.class).setParameter("name", name).setParameter("pwd", password).getSingleResult() != null;
		} catch (NoResultException nre) {
			return false;
		}
	}

}
